package App.Service;

import App.Model.Chat.GroupResponse;
import App.Model.WeChat.*;
import App.Model.Xinge.*;
import App.Repository.XinGePushRepository;
import App.Tencent.SignatureManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.cms.PasswordRecipientId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Random;

/**
 * Created by xw on 2019/1/11.
 * https://xg.qq.com/docs/server_api/v3/rest_api_summary.html
 * tecent xinge push servcie
 */


@Service
public class XingeService {

    // @Autowired
    private RestTemplate restTemplate = new RestTemplate();

    @Autowired
    private XingeConfig _xingetConfig;

    private Random rand = new Random(99999999);
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private Object ApaasLoinRequest;

    //get android sign
    private String getAndroidSign() throws Exception {

        String androidAppid = _xingetConfig.getAndroidAppid();
        String androidSecretkey = _xingetConfig.getAndroidSecretkey();
        String _sign = androidAppid + ":" + androidSecretkey;
        String base64_auth_string = base64Encode(_sign);
        return base64_auth_string;

    }

    //get ios sign
    private String getIosSign() throws Exception {
        String iosAppid = _xingetConfig.getIosAppid();
        String iosSecretkey = _xingetConfig.getIosSecretkey();
        String _sign = iosAppid + ":" + iosSecretkey;

        String base64_auth_string = base64Encode(_sign);
        return base64_auth_string;
    }

    public String base64Encode(String s) throws Exception {
        String res = new sun.misc.BASE64Encoder().encode(s.getBytes("UTF-8"));
        return res;
    }

    public String getAuthorizationString(String base64_auth_string) {
        return "Basic " + base64_auth_string;
    }


    public String pushMessage(String taskId, String reminderId, List<String> userids, String title, String content, String pushType) throws Exception {
        pushMessageAndroid(taskId, reminderId, userids, title, content, pushType);
        pushMessageIos(taskId, reminderId, userids, title, content);
        return "";
    }

    public String pushMessage(String taskId, String reminderId, List<String> userids, String title, String content) throws Exception {
        return pushMessage(taskId, reminderId, userids, title, content, null);
    }

    //给android推送消息
    public String pushMessageAndroidBase(List<String> userids, String title, String content) throws Exception {

        String _result = "";
        try {
            String strUserid = "";
            AndoridPushRequest _pushRequest = new AndoridPushRequest();

            //设置账号
            _pushRequest.setAccount_list(userids);

            //多账号推送
            _pushRequest.setAudience_type("account_list");
            _pushRequest.setPlatform("android");
            _pushRequest.setMessage_type("message");

            if (title.isEmpty()) {
                title = "法力任务提醒";
            }

            AndroidPushMessage _androidMessage = new AndroidPushMessage();
            _androidMessage.setTitle(title);
            _androidMessage.setContent(content);
            XinGeCustomerContent _customerContent=new XinGeCustomerContent();
            //_androidMessage.setCustom_content(_customerContent);
            AndroidInnerMessageBody _androidBody=new AndroidInnerMessageBody();
            _androidBody.setCustom_content(_customerContent);
            _androidMessage.setAndroid(_androidBody);

            _pushRequest.setMessage(_androidMessage);

            String requestJson = JSONObject.toJSONString(_pushRequest);
            logger.info("xinge android push request:" + requestJson);

            String _sign = getAndroidSign();
            HttpHeaders headers = new HttpHeaders();
            headers.set(HttpHeaders.AUTHORIZATION, "Basic " + _sign);
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.setCacheControl(CacheControl.noCache());

            if (isPushMessage()) {
                HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
                String pushUrl = getPushUrl();
                ResponseEntity<String> responseEntity = this.restTemplate.exchange(pushUrl, HttpMethod.POST, request, String.class);
                _result = responseEntity.getBody();
                logger.info("xinge android push response:" + _result);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    //给ios推送消息
    public String pushMessageIosBase(List<String> userids, String title, String content) throws Exception {

        String _result = "";
        try {
            String strUserid = "";
            if (title.isEmpty()) {
                title = "法力任务提醒";
            }
            IosAlertMessage _alterMessage = new IosAlertMessage();
            _alterMessage.setSubtitle("this is subtitle");

            IosInnerMessage _innerMessage = new IosInnerMessage();
            _innerMessage.setAps(_alterMessage);

            IosPushMessage _pushMessage = new IosPushMessage();
            _pushMessage.setTitle(title);
            _pushMessage.setContent(content);
            _pushMessage.setIos(_innerMessage);

            XinGeCustomerContent _customer=new XinGeCustomerContent();
           //_customer.setPushType("");
            //_customer.setTaskid();

            IosPushRequest _pushRequest = new IosPushRequest();
            _pushRequest.setPlatform("ios");
            _pushRequest.setMessage_type("notify");
            _pushRequest.setAudience_type("account_list");
            _pushRequest.setAccount_list(userids);
            _pushRequest.setEnvironment(_xingetConfig.getIosenviroment());
            _pushRequest.setMessage(_pushMessage);

            String requestJson = JSONObject.toJSONString(_pushRequest);
            logger.info("xinge ios push request:" + requestJson);

            String _sign = getIosSign();
            HttpHeaders headers = new HttpHeaders();
            headers.set(HttpHeaders.AUTHORIZATION, "Basic " + _sign);
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.setCacheControl(CacheControl.noCache());

            if (isPushMessage()) {
                HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
                String pushUrl = getPushUrl();
                ResponseEntity<String> responseEntity = this.restTemplate.exchange(pushUrl, HttpMethod.POST, request, String.class);
                _result = responseEntity.getBody();
                logger.info("xinge ios push response:" + _result);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    public String pushMessageBase(List<String> userids, String title, String content) throws Exception {

        pushMessageAndroidBase(userids, title, content);
        pushMessageIosBase(userids, title, content);
        return "";
    }

    //给android推送消息
    public String pushMessageAndroid(String taskId, String reminderId, List<String> userids, String title, String content, String pusherType) throws Exception {
        if(pusherType == null || pusherType.equals("")){
            pusherType = "taskAlert";
        }
        String _result = "";
        try {
            String strUserid = "";
            AndoridPushRequest _pushRequest = new AndoridPushRequest();

            //设置账号
            _pushRequest.setAccount_list(userids);

            //多账号推送
            _pushRequest.setAudience_type("account_list");
            _pushRequest.setPlatform("android");
            _pushRequest.setMessage_type("notify");
            _pushRequest.setExpire_time(0);


            if (title.isEmpty()) {
                title = "法力任务提醒";
            }

            AndroidPushMessage _androidMessage = new AndroidPushMessage();
            _androidMessage.setTitle(title);
            _androidMessage.setContent(content);

            XinGeCustomerContent _customerContent=new XinGeCustomerContent();
            _customerContent.setPushType(pusherType);
            _customerContent.setTaskid(taskId);
            //_androidMessage.setCustom_content(_customerContent);

            AndroidInnerMessageBody _androidBody=new AndroidInnerMessageBody();
            _androidBody.setCustom_content(_customerContent);
            _androidMessage.setAndroid(_androidBody);

            _pushRequest.setMessage(_androidMessage);

            String requestJson = JSONObject.toJSONString(_pushRequest);
            logger.info("xinge push request:" + requestJson);


            String _sign = getAndroidSign();
            HttpHeaders headers = new HttpHeaders();
            headers.set(HttpHeaders.AUTHORIZATION, "Basic " + _sign);
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.setCacheControl(CacheControl.noCache());

            if (isPushMessage()) {
                HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
                String pushUrl = getPushUrl();
                ResponseEntity<String> responseEntity = this.restTemplate.exchange(pushUrl, HttpMethod.POST, request, String.class);
                _result = responseEntity.getBody();

                try {
                    XinGePushRepository _pushRepository = new XinGePushRepository();
                    _pushRepository.savePushHistory(taskId, reminderId, content, requestJson, _result, "Android");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                logger.info("xinge push response:" + _result);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    //给ios推送消息
    public String pushMessageIos(String taskId, String reminderId, List<String> userids, String title, String content) throws Exception {

        String _result = "";
        try {
            String strUserid = "";
            if (title.isEmpty()) {
                title = "法力任务提醒";
            }
            IosAlertMessage _alterMessage = new IosAlertMessage();
            _alterMessage.setSubtitle("this is subtitle");

            IosInnerMessage _innerMessage = new IosInnerMessage();
            _innerMessage.setAps(_alterMessage);

            IosPushMessage _pushMessage = new IosPushMessage();
            _pushMessage.setTitle(title);
            _pushMessage.setContent(content);
            _pushMessage.setIos(_innerMessage);

            XinGeCustomerContent _customer=new XinGeCustomerContent();
            _customer.setPushType("taskAlert");
            _customer.setTaskid(taskId);
            //_pushMessage.setCustom(_customer);

            _innerMessage.setCustom(_customer);

            IosPushRequest _pushRequest = new IosPushRequest();
            _pushRequest.setPlatform("ios");
            _pushRequest.setMessage_type("notify");
            _pushRequest.setAudience_type("account_list");
            _pushRequest.setExpire_time(0);
            // _pushRequest.setAudience_type("all");

            _pushRequest.setAccount_list(userids);
            _pushRequest.setEnvironment(_xingetConfig.getIosenviroment());
            _pushRequest.setMessage(_pushMessage);

            String requestJson = JSONObject.toJSONString(_pushRequest);
            logger.info("xinge android push request:" + requestJson);

            String _sign = getIosSign();
            HttpHeaders headers = new HttpHeaders();
            headers.set(HttpHeaders.AUTHORIZATION, "Basic " + _sign);
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.setCacheControl(CacheControl.noCache());

            if (isPushMessage()) {
                HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
                String pushUrl = getPushUrl();
                ResponseEntity<String> responseEntity = this.restTemplate.exchange(pushUrl, HttpMethod.POST, request, String.class);
                _result = responseEntity.getBody();
                logger.info("xinge ios push result:" + _result);
                try {
                    XinGePushRepository _pushRepository = new XinGePushRepository();
                    _pushRepository.savePushHistory(taskId, reminderId, content, requestJson, _result, "IOS");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }


        return _result;
    }


    private HttpHeaders createHttpHeaders(String user, String password) {
        String notEncoded = user + ":" + password;
        String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", "Basic " + encodedAuth);
        return headers;
    }

    private String getPushUrl() {
        return _xingetConfig.getRooturl() + _xingetConfig.getPushurl();
    }


    private boolean isPushMessage() {
        return _xingetConfig.isPushmessage();
    }

    public String pushCustomerMessageAndroid(String taskId, String reminderId, List<String> userids, String title, String content,XinGeCustomerContent CustomerMessage) throws Exception {

        String _result = "";
        try {
            String strUserid = "";
            AndoridPushRequest _pushRequest = new AndoridPushRequest();

            //设置账号
            _pushRequest.setAccount_list(userids);

            //多账号推送
            _pushRequest.setAudience_type("account_list");
            _pushRequest.setPlatform("android");
            _pushRequest.setMessage_type("notify");
            _pushRequest.setExpire_time(0);


            if (title.isEmpty()) {
                title = "法力任务提醒";
            }

            AndroidPushMessage _androidMessage = new AndroidPushMessage();
            _androidMessage.setTitle(title);
            _androidMessage.setContent(content);

            AndroidInnerMessageBody _androidBody=new AndroidInnerMessageBody();
            _androidBody.setCustom_content(CustomerMessage);
            _androidMessage.setAndroid(_androidBody);
            //_androidMessage.setCustom_content(CustomerMessage);
            _pushRequest.setMessage(_androidMessage);

            String requestJson = JSONObject.toJSONString(_pushRequest);
            logger.info("xinge push request:" + requestJson);


            String _sign = getAndroidSign();
            HttpHeaders headers = new HttpHeaders();
            headers.set(HttpHeaders.AUTHORIZATION, "Basic " + _sign);
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.setCacheControl(CacheControl.noCache());

            if (isPushMessage()) {
                HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
                String pushUrl = getPushUrl();
                ResponseEntity<String> responseEntity = this.restTemplate.exchange(pushUrl, HttpMethod.POST, request, String.class);
                _result = responseEntity.getBody();

                try {
                    XinGePushRepository _pushRepository = new XinGePushRepository();
                    _pushRepository.savePushHistory(taskId, reminderId, content, requestJson, _result, "Android");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                logger.info("xinge push response:" + _result);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    public String pushCustomerMessageIos(String taskId, String reminderId, List<String> userids, String title, String content,XinGeCustomerContent CustomerMessage) throws Exception {

        String _result = "";
        try {
            String strUserid = "";
            if (title.isEmpty()) {
                title = "法力任务提醒";
            }
            IosAlertMessage _alterMessage = new IosAlertMessage();
            _alterMessage.setSubtitle("this is subtitle");

            IosInnerMessage _innerMessage = new IosInnerMessage();
            _innerMessage.setAps(_alterMessage);
            _innerMessage.setCustom(CustomerMessage);

            IosPushMessage _pushMessage = new IosPushMessage();
            _pushMessage.setTitle(title);
            _pushMessage.setContent(content);
            _pushMessage.setIos(_innerMessage);
          //  _pushMessage.setCustom(CustomerMessage);
           // _pushMessage.setCustom1("bar");

          /*  List<String>  _tmpList=new ArrayList<>();
            _tmpList.add("bang");
            _tmpList.add("whiz");
            _pushMessage.setCustom2(_tmpList);*/

            IosPushRequest _pushRequest = new IosPushRequest();
            _pushRequest.setPlatform("ios");
            _pushRequest.setMessage_type("notify");
            _pushRequest.setAudience_type("account_list");
            _pushRequest.setExpire_time(0);
            // _pushRequest.setAudience_type("all");

            _pushRequest.setAccount_list(userids);
            _pushRequest.setEnvironment(_xingetConfig.getIosenviroment());
            _pushRequest.setMessage(_pushMessage);

            String requestJson = JSONObject.toJSONString(_pushRequest);
            logger.info("xinge android push request:" + requestJson);

            String _sign = getIosSign();
            HttpHeaders headers = new HttpHeaders();
            headers.set(HttpHeaders.AUTHORIZATION, "Basic " + _sign);
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.setCacheControl(CacheControl.noCache());

            if (isPushMessage()) {
                HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
                String pushUrl = getPushUrl();
                ResponseEntity<String> responseEntity = this.restTemplate.exchange(pushUrl, HttpMethod.POST, request, String.class);
                _result = responseEntity.getBody();
                logger.info("xinge ios push result:" + _result);
                try {
                    XinGePushRepository _pushRepository = new XinGePushRepository();
                    _pushRepository.savePushHistory(taskId, reminderId, content, requestJson, _result, "IOS");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }


        return _result;
    }




    public String testWeChat(String code)
    {

          //get access token
            //HttpEntity<String> request = new HttpEntity<String>();
            String pushUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwf5c7653a822def73&corpsecret=KZssiL63W7oB-bClZdN8l_EK-iz4kVrEeFTxwykxYq0";
            ResponseEntity<String> responseEntity = this.restTemplate.exchange(pushUrl, HttpMethod.GET, null, String.class);
           String    _result = responseEntity.getBody();

            GetAccessTokenResponse _groupResponse = JSON.parseObject(_result, GetAccessTokenResponse.class);
             String _actionToken = _groupResponse.getAccess_token();

           String _getUserInfoUrl="https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=%s&code=%s";
           _getUserInfoUrl=String.format(_getUserInfoUrl,_actionToken,code);
           responseEntity = this.restTemplate.exchange(_getUserInfoUrl, HttpMethod.GET, null, String.class);
           _result = responseEntity.getBody();
           GetUserInfoResponse _groupResponse2 = JSON.parseObject(_result, GetUserInfoResponse.class);


        //get token
        HttpHeaders headers1 = new HttpHeaders();
        headers1.setContentType(MediaType.APPLICATION_JSON_UTF8);

        App.Model.WeChat.ApaasLoinRequest  _loginRequest=new App.Model.WeChat.ApaasLoinRequest();
        _loginRequest.setAccountinfocode("1227115891020402688");
        _loginRequest.setOpentypecode("sanxian-wechat-server");
        _loginRequest.setOpentypesecret("123456");
        _loginRequest.setClienttypecode(2);
        String requestJson = JSONObject.toJSONString(_loginRequest);
        String _loginUrl="http://183.63.72.243:17000/api/auth/openlogin";
        HttpEntity<String> _login = new HttpEntity<String>(requestJson, headers1);
        ResponseEntity<String> _loginBody= this.restTemplate.exchange(_loginUrl, HttpMethod.POST, _login, String.class);
        String  _responseString=_loginBody.getBody();
        ApaasLoinResponseWrapper _groupResponse3 = JSON.parseObject(_responseString, ApaasLoinResponseWrapper.class);
       String _apaasToken= _groupResponse3.getResp_data().getToken();


        //get accountinfo
        String _accountInfoUrl="http://183.63.72.243:17000/api/teapi/dy-biz/1232313272473096285/1232313272473096284";
        GetCrmAccountRequest  _crmAccountRequest=new GetCrmAccountRequest();
        WebChatAccountInfo  _webChatAccount=new WebChatAccountInfo();
        String _userId=_groupResponse2.getUserId();
        _webChatAccount.setWechat_account(_userId);
        _crmAccountRequest.setCrm_wechat_account(_webChatAccount);


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.setCacheControl(CacheControl.noCache());
        headers.set("token",_apaasToken);

        String requestJson2 = JSONObject.toJSONString(_crmAccountRequest);
        HttpEntity<String> _login2 = new HttpEntity<String>(requestJson2, headers);
        ResponseEntity<String> _loginBody2= this.restTemplate.exchange(_accountInfoUrl, HttpMethod.POST, _login2, String.class);


        String  __loginBody2String=_loginBody2.getBody();
        GetCrmAccountResponseWrapper _groupResponse4 = JSON.parseObject(__loginBody2String, GetCrmAccountResponseWrapper.class);
        String _accountInfoCode=  _groupResponse4.getResp_data().getCrm_wechat_account().get(0).getAccountinfocode();


        //get the user token
        _loginRequest.setAccountinfocode(_accountInfoCode);
        ResponseEntity<String> _loginBody5= this.restTemplate.exchange(_loginUrl, HttpMethod.POST, _login, String.class);
        ApaasLoinResponseWrapper _groupResponse5 = JSON.parseObject(_loginBody.getBody(), ApaasLoinResponseWrapper.class);


         String redirectUrl = "http://183.63.72.243:17000/#/loading?token=%s&refreshtoken=%s&tokenexpires=%s&tenantcode=%s&productversioncode=%s&uid=&pid=";
        String _newToken=_groupResponse5.getResp_data().getToken();
        String _refreshtoken=_groupResponse5.getResp_data().getRefreshtoken();
        String _tokenexpires=_groupResponse5.getResp_data().getTokenexpires();


        String _tenantcode=_groupResponse5.getResp_data().getTenants().get(0).getCode();
        String _productversioncode=   _groupResponse5.getResp_data().getTenants().get(0).getProductversionlist().get(0).getCode();

       String _finalString=  String.format(redirectUrl,_newToken,_refreshtoken,_tokenexpires,_tenantcode,_productversioncode);
        return  _finalString;




    }




}
